# == Schema Information
#
# Table name: devices
#
#  id          :integer          not null, primary key
#  account_id  :integer          not null
#  name        :string(255)
#  company     :string(255)
#  industry    :string(255)
#  province    :string(255)
#  city        :string(255)
#  district    :string(255)
#  longitude   :string(255)
#  latitude    :string(255)
#  cantact     :string(255)
#  phone       :string(255)
#  online_date :datetime
#  created_at  :datetime
#  updated_at  :datetime
#  token       :string(255)
#  password    :string(255)
#

class Device < ActiveRecord::Base
  belongs_to :account
  has_many :radchecks, :as => :radcheckable, :dependent => :destroy

  validates_presence_of :account_id, :token, :name, :password
  validates_uniqueness_of :token, :name

  before_create :generate_token
  after_create :set_radcheck_attr
  after_save :update_radcheck_attr

  protected
  def set_radcheck_attr
    self.radchecks.create(
      :username => "d_#{self.name}",
      :attr => Settings.check_types['password'],
      :op => "==", 
      :value => self.password
    )
  end

  def update_radcheck_attr
    if self.password_changed? 
      radcheck = self.radchecks.where(:attr => Settings.check_types['password']).first
      if radcheck
        radcheck.update_column(:value, self.password)
      else
        set_radcheck_attr
      end
    end
  end

  def generate_token
    loop do 
      random_token = Devise.friendly_token
      unless Device.exists?(:token => random_token)
        self.token = random_token
        break
      end
    end
  end
end
